#include <mqueue.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  int flags, opt;
  mqd_t mqd;
  unsigned int prio;
  void *buffer;
  struct mq_attr attr;
  ssize_t numRead;
  flags = O_RDONLY;
  while ((opt = getopt(argc,argv,"n")) != -1) {
    switch (opt) {
    case 'n': 
      flags |= O_NONBLOCK;
      break;
    default:
      printf("wrong option\n");
    }
  }
  if (optind >= argc)
    printf("wrong usage\n");
  mqd = mq_open(argv[optind], flags);
  if(mqd == (mqd_t)-1)
    printf("Failed to open mq %s\n", argv[optind]);
  if (mq_getattr(mqd, &attr) == -1)
    printf("Failed to get attributes\n");
  buffer = malloc(attr.mq_msgsize);
  if (buffer == NULL)
    printf("Failed to allocate memory\n");
  numRead = mq_receive(mqd,(char*)buffer, attr.mq_msgsize, &prio);
  if (numRead == -1)
    printf("Failed to recieve msg\n");
  printf("Read %ld bytes; priority = %u\n",(long)numRead, prio);
  if (write(STDOUT_FILENO, buffer, numRead) == -1)
    printf("Failed to write\n");
  write(STDOUT_FILENO, "\n",1);
  return 0;
}
